package com.feinno.urcs.group.dao;

import com.feinno.database.DataRow;
import com.feinno.database.DataTable;
import com.feinno.database.Database;
import com.feinno.urcs.group.api.GroupIndexService;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.util.URIUtils;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;

/**
 * Created by honghao on 5/4/15.
 * 使用飞信侧的 GGRP_SearchGroup 表, 是SQLServer ,废弃, 使用飞信的Impl. 如果使用这个 需要重新实现逻辑
 */
@Deprecated
@ServiceImplementation
public class GroupIndexServiceImpl implements GroupIndexService {
	//TODO 后续可能需要增加对GroupType 的 判断.
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupIndexServiceImpl.class);
	private int poolId = 0;
	@FieldSetter("${GGRPDB}")
	private Database ggrpDb;

	@Override
	public GroupIndex getGroupById(int groupId) throws SQLException {
		String sql = "SELECT LogicPool FROM GGRP_SearchGroup where GroupId=?";
		GroupIndex index = null;
		if (groupId == 0) return null;
		DataTable dt = ggrpDb.executeTable(sql, groupId);
		if (dt.getRows().size() == 1) {
			int logicalPoolId = dt.getRow(0).getInt(1);
			index = new GroupIndex(groupId, logicalPoolId);
		}
		return index;
	}

	@Override
	public GroupIndex getGroupByUri(String groupUri) throws SQLException {
		GroupIndex index = getGroupById(URIUtils.getGroupIdFromUri(groupUri));
		if (index != null) index = getGroupById(index.getGroupId());
		return index;
	}

	@Override
	public GroupIndex getGroupByConversationId(String conversationId) throws SQLException {
		String sql = "SELECT * FROM GGRP_SearchGroup where ConversationId=?";
		DataTable dt = ggrpDb.executeTable(sql, conversationId);
		if (dt.getRows().size() == 1) {
			DataRow row = dt.getRow(0);
			int groupId = row.getInt("GroupId");
			int pool = row.getInt("LogicPool");
			return new GroupIndex(groupId, pool);
		} else {
			return null;
		}
	}

	@Override
	public GroupIndex createGroup(String conversationId, String subject, MobileNo adminMobileNo) throws SQLException {
		String insertsql = "INSERT INTO GGRP_SearchGroup (LogicPool,ConversationId) VALUES ( ?, ?)";
		ggrpDb.executeNonQuery(insertsql, poolId, conversationId);
		String getgroupidsql = "SELECT GroupID FROM GGRP_SearchGroup  WHERE ConversationId =?";
		DataTable table = ggrpDb.executeTable(getgroupidsql, conversationId);
		int groupId = table.getRow(0).getInt(1);
		GroupIndex index = new GroupIndex(groupId, 0);
		return index;
	}

	@Override
	public boolean deleteGroup(int groupId) throws SQLException {
		String sql = "delete from GGRP_SearchGroup where GroupId =?";
		int ret = ggrpDb.executeNonQuery(sql, groupId);
		if (ret != 1) {
			LOGGER.error("deleteGroup Unexcepted ret=" + ret);
			return false;
		} else {
			return true;
		}
	}
}
